#include "savepathdialog.h"


SavePathDialog::SavePathDialog(QWidget *parent) :
            kdk::KDialog(parent)
{
    this->setWindowModality(Qt::ApplicationModal);
    this->setFixedSize(QSize(424,186));
    this->setFocus();

    QWidget*mainwindow = mainWidget();
    QGridLayout *layout = new QGridLayout(mainwindow);
    m_pathLabel = new QLabel;
    m_pathLabel->setText(tr("Storage Path:")+getSavePath());
    m_modifyBtn = new QPushButton;
    m_modifyBtn->setFixedSize(QSize(88,33));
    m_modifyBtn->setText(tr("Modify"));
    m_confirmBtn = new QPushButton;
    m_confirmBtn->setFixedSize(QSize(88,33));
    m_confirmBtn->setText(tr("Confirm"));
    m_confirmBtn->setEnabled(false);

    layout->addWidget(m_pathLabel,0,0);
    layout->addWidget(m_modifyBtn,0,1);
    layout->addWidget(m_confirmBtn,1,1);
    layout->setContentsMargins(24, 0, 24, 0);

    connect(m_modifyBtn,&QPushButton::clicked,this,&SavePathDialog::onModifyBtnClicked);
}

void SavePathDialog::updateLabel(QString savepath)
{
    m_pathLabel->setText(tr("Storage Path:")+savepath);
    m_pathLabel->setToolTip(savepath);
}

QString SavePathDialog::getSavePath()
{
    QString dirPath = QDir::homePath() + "/.cache/theme-build";
    QString filePath = dirPath + "/savepath.conf";

    QFile file(filePath);

    if (file.exists() && file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream stream(&file);
        QString savePath = stream.readAll();
        file.close();

        return savePath;
    } else {
        qDebug() << "Error: File does not exist or cannot be opened.";
    }
}

void SavePathDialog::onModifyBtnClicked()
{
    QString newFilePath = QFileDialog::getExistingDirectory(this, tr("Select Directory"),QDir::homePath());
    if(newFilePath != nullptr){
        m_savepath = newFilePath;
        emit savePathUpdate(newFilePath);
        this->updateLabel(newFilePath);
        m_confirmBtn->setEnabled(true);
        connect(m_confirmBtn,&QPushButton::clicked,this,&SavePathDialog::close);
    }else{
        qDebug()<<"savepath is null";
    }
}
